package com.zyn.qianwen.user.service.impl;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.fastjson.JSONObject;
import com.zyn.qianwen.user.dao.TbQuestionDao;
import com.zyn.qianwen.user.entity.Result;
import com.zyn.qianwen.user.entity.TbQuestion;
import com.zyn.qianwen.user.service.ChatService;
import com.zyn.qianwen.user.util.JwtUtil;
import com.zyn.qianwen.user.util.QianWenChat;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    StringRedisTemplate redis;
    @Autowired
    TbQuestionDao tbQuestionDao;

    @Override
    public GenerationResult chatAi() throws Exception {
        return  QianWenChat.callWithMessage("百度的网址是");
    }

    @Override
    public Result chatAiAndQuestion(HttpServletRequest request, TbQuestion tbQuestion) throws Exception {
        String accessToken = null;
        try {
            accessToken= request.getHeaders("accessToken").nextElement();
        }catch (Exception e){
            return Result.faled(400401,"重新登陆");
        };
        if (StringUtils.isEmpty(accessToken)){
            return Result.faled(400402,"登录超时");
        }
        Claims claims = null;
        try {
            claims=claims(accessToken);
        }catch (Exception e){
            return Result.faled(400401,"重新登陆");
        }
        String id = claims.getId();
        String s = redis.opsForValue().get("gene_token" + id);
        if (StringUtils.isEmpty(s)){
            return Result.faled(400401,"重新登陆");
        }
        GenerationResult generationResult = QianWenChat.callWithMessage(tbQuestion.getQuestion());
        TbQuestion tbQuestion1 = new TbQuestion();
        tbQuestion1.setQuestion(tbQuestion.getQuestion());
        tbQuestion1.setMessage(generationResult.toString());
        tbQuestion1.setLoginId(Integer.parseInt(id));
        tbQuestionDao.insert(tbQuestion1);
        return Result.SUCCESS(generationResult);
    }


    public Claims claims(String accessToken){
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseJWT(accessToken);
        return claims;
    }
}
